package com.hice.demo.java.concurrent.forkjoinpool;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;

/**
 * RecursiveAction没有返回值
 * @author hyson
 * @create 2017-03-13 13:25
 */
public class MyRecursiveActionDemo extends RecursiveAction {
    private long workLoad = 0;

    public MyRecursiveActionDemo(long workLoad) {
        this.workLoad = workLoad;
    }

    @Override
    protected void compute() {
        if (this.workLoad > 16) {
            System.out.println("Splitting workLoad : " + this.workLoad);

            List<MyRecursiveActionDemo> subtasks = new ArrayList<>();

            subtasks.addAll(createSubtasks());

            for (RecursiveAction subtask : subtasks) {
                subtask.fork();
            }

        } else {
            System.out.println("Doing workLoad myself: " + this.workLoad);
        }
    }

    private List<MyRecursiveActionDemo> createSubtasks() {
        List<MyRecursiveActionDemo> subtasks = new ArrayList<>();

        MyRecursiveActionDemo subtask1 = new MyRecursiveActionDemo(this.workLoad / 2);
        MyRecursiveActionDemo subtask2 = new MyRecursiveActionDemo(this.workLoad / 2);

        subtasks.add(subtask1);
        subtasks.add(subtask2);

        return subtasks;
    }

    public static void main(String[] args) {
        MyRecursiveActionDemo myRecursiveActionDemo = new MyRecursiveActionDemo(24);
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        forkJoinPool.invoke(myRecursiveActionDemo);
    }
}
